package apof.services
{
	import apof.util.xml.TransitionsGetter;
	import flash.events.Event;
	import apof.util.ConfigureReader;
	import mx.collections.ArrayCollection;
	import apof.model.Transection;
	import apof.dao.Dao;
	import apof.util.Hasher;
	import flash.utils.Dictionary;
	import flash.system.Updater;
	
	public class SynService
	{
		
		private static var tg:TransitionsGetter;
		public static var tc:TransactionCommiter;
		private static var hashTable:Dictionary=initHashTable();
		
		public static function setUP(u:String,p:String):void {
			tg=new TransitionsGetter(u,"user");
			tc= new TransactionCommiter(u,p);
			update();
		}
		
		private static function initHashTable():Dictionary {
			var dic:Dictionary=new Dictionary();
			var arr:Array=Dao.dp.retriveAll(Transection);
			for each(var tr:Transection in arr) {
				dic[tr.hashCode]=tr;
			}
			return dic;
		}
		
		public static function update():void {
			//upload
//			var newTrs:Array=Dao.dp.retriveAll(Transection,null,null,null,"absoluteTime",true,5);
//			for each(var tr:Transection in newTrs) {
//				if(tr.offline && tr.amount<0) {
//					tr.offline=false;					
//					Dao.dp.update(tr);
//					tc.commit(tr.toString());
//				}
//			}
			//download
//			tg.addEventListener(Event.COMPLETE,getTransitions);
		}
		
		public static function getTransitions(e:Event):void{
			var list:ArrayCollection=tg.getTransitions();
			for each(var trObj:Object in list) {
				
				var partern:RegExp=/(花了?)?([0-9.]+)元(买了?)?([\u4e00-\u9fa5a-zA-Z0-9_]+)(\.|,|$|，|。|!|！)(.+)?/;
				var res:Object=partern.exec(trObj.text);
				if(res) {
					var tr:Transection=new Transection();
					tr.name=res[4];
					tr.amount=res[2];
					tr.description=res[6];
					tr.time=new Date(Date.parse(trObj.time));
					var hash:int=tr.hashCode;
					if(hashTable[hash]==null) {
						tr.offline=false;
						Dao.dp.create(tr);						
					}
				}
				
			}
			
		}
	}
}